package com.atguigu.lease.web.admin.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exceptionHandle.BusiException;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserService systemUserService;


    @Override
    public CaptchaVo getCaptcha() {
//        todo 生成验证码图片  设置验证码的key 和 value  存入redis 并设置过期时间 最后以vo的方式返回对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 3);
        String verCode = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(key, verCode,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.MINUTES);
        String image = specCaptcha.toBase64();
        return new CaptchaVo(image,key);
    }

    @Override
    public String login(LoginVo loginVo) {
//        todo 判断前端传的vo是否有内容
        if(!StringUtils.hasText(loginVo.getUsername())){
            throw new BusiException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        if(!StringUtils.hasText(loginVo.getPassword())){
            throw new BusiException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        if(!StringUtils.hasText(loginVo.getCaptchaKey())){
            throw new BusiException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        if(!StringUtils.hasText(loginVo.getCaptchaCode())){
            throw new BusiException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

//        再判断是否和redis里的验证码存储一致
        String redisCaptcha = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if(!loginVo.getCaptchaCode().equalsIgnoreCase(redisCaptcha)){
            throw new BusiException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
//        根据username查到数据库中的用户 用户是否为空 判断是否是同一个密码  用户状态是否是禁用
        SystemUser systemUser = systemUserService.getOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, loginVo.getUsername()));
        if(systemUser == null){
            throw new BusiException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        if(!DigestUtils.md5Hex(loginVo.getPassword()).equals(systemUser.getPassword())){
            throw  new BusiException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        if(systemUser.getStatus() == BaseStatus.DISABLE){
            throw new BusiException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

//        todo 生成token  存入redis 并返回token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
//        后续每一个请求都是要带token 所以要把token通过拦截器存到threadlocal里
    }

    @Override
    public SystemUserInfoVo getSystemUserInfoVo(Long userId) {
        SystemUser systemUser = systemUserService.getById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getUsername());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }


}
